package edu;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Aguest on 2018/6/17.
 */
    public class AddUserServlet extends HttpServlet {

        @Override
        protected void doPost(HttpServletRequest request,
                              HttpServletResponse response)
                throws ServletException, IOException {

            // 解决数据库中文乱码问题
            request.setCharacterEncoding("utf-8");

            // 得到用户输入的信息
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            // 3 + 1
            Connection connection = null;
            Statement statement = null;

            // 221
            String sql = "insert into t_users(username, password) values('"+username+"','"+password+"')";

            try {
                Class.forName("com.mysql.jdbc.Driver");

                connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/sctu_javaweb_2018?serverTimezone=UTC",
                        "root",
                        "123456");

                statement = connection.createStatement();
                statement.execute(sql);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }


            // 解决中文乱码问题。
            response.setCharacterEncoding("gbk");

            PrintWriter out = response.getWriter();
            out.write("<h1>成功添加用户！</h1>");
            out.write("<a href='userList.jsp'>返回首页</a>");


        }
}
